<template>
  <div>
    <el-tabs class="protect" v-model="protectKey" @tab-change="handleProtectTabChange">
      <el-tab-pane v-for="protectItem in protectArr" :key="protectItem.key" :label="protectItem.name"
        :name="protectItem.key">
        <div v-if="protectKey === 'form'">
          <div class="form-container">
            <div class="form-contain">
              <el-input v-model="searchKey" clearable placeholder="输入表单名称" />
              <div class="form-list">
                <el-menu v-if="!checkMode" style="--el-menu-active-color: var(--el-color-primary)" default-active="0"
                  @select="index => handleFormSelect(index)">
                  <el-menu-item v-for="(item, key) in searchResult" :index="key" :key="item.id">
                    {{ item.content.form.label }}
                  </el-menu-item>
                </el-menu>
                <div class="checkBox" v-else>
                  <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="checkList" @change="handleCheckedCitiesChange">
                    <el-checkbox v-for="(item, key) in searchResult" :index="key" :key="item.id"
                      :label="item.content.form.label" />
                  </el-checkbox-group>
                </div>
              </div>
            </div>
            <div class="">
              <div class="form-buttons">
                <el-button v-if="!checkMode" @click="checkMode = true">
                  批量设置
                </el-button>
                <el-button v-if="checkMode" @click="() => {
                  checkMode = false;
                  checkList = [];
                }
                  ">
                  取消批量设置
                </el-button>
                <el-button @click="saveAll" v-if="checkMode">
                  保存批量设置
                </el-button>
              </div>
              <el-form class="protect-form">
                <el-form-item v-for="(val, key) in protectOpt" :key="key" :label="(protectItems[key] || key) + ':'"
                  label-width="200px">
                  <el-radio-group v-model="val.status" @change="status => handleSaveOpt(status, val, key)">
                    <el-radio :label="3">保护</el-radio>
                    <el-radio v-if="limitShow(key)" @click="hanleShowTemp(val, val, key)" :label="2" style="width: 80px"
                      :disabled="val.limit == 3">部分保护</el-radio>
                    <div class="el-radio" style="width: 80px" v-else></div>
                    <el-radio :label="1" :disabled="val.limit == 3 || val.limit === 2">不保护</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
        <div v-else>
          <el-form class="protect-form" v-if="protectOpt.length">
            <el-form-item v-for="(opt, key) in protectOpt" :key="key" :label="opt.objectLabel" label-width="200px">
              <el-radio-group v-if="opt.detail" v-model="opt.detail.status" @change="handleSaveOpt(null, null, key)">
                <el-radio :label="3">保护</el-radio>
                <el-radio :disabled="opt.detail.limit == 3" :label="1">不保护</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <el-empty v-else></el-empty>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import feed1 from "../feed.json";
import feed2 from "../protectconfig.json";

const limitStatusArr = [
  "field",
  "rowformula",
  "checkformula",
  "sumformula",
  "referencefilter",
  "queryfilter",
  "apptreefilter",
  "customfilter"
];
const protectItem = {
  field: "字段",
  customquerytemplates: "自定义查询模板",
  customviewtemplates: "自定义查看模板",
  excelviewtemplates: "excel视图模板",
  charts: "图表",
  trigger: "回写公式",
  report: "报表公式",
  rowformula: "行间公式",
  checkformula: "校验公式",
  sumformula: "汇总行公式",
  referencefilter: "引用过滤公式",
  queryfilter: "查询过滤公式",
  apptreefilter: "导航树过滤公式",
  customfilter: "自定义查询过滤公式"
};
export default {
  data() {
    return {
      protectItems: protectItem,
      protectKey: "form",
      currentProtectForm: null,
      protectOpt: [],
      protectFormList: [],
      templateVisible: false,
      template: [],
      searchKey: "",
      searchResult: [],
      checkAll: false,
      isIndeterminate: false,
      protectArr: [
        {
          name: "表单",
          key: "form"
        },
        {
          name: "导航树",
          key: "apptree"
        },
        {
          name: "门户",
          key: "portal"
        },
        {
          name: "网站",
          key: "website"
        },
        {
          name: "数据分析",
          key: "adhoc"
        },
        {
          name: "流程",
          key: "workflow"
        },
        {
          name: "微应用 ",
          key: "microapp"
        },
        {
          name: "问卷 ",
          key: "survey"
        }
      ],

      checkMode: false,
      checkList: []
    };
  },

  computed: {
    spaceId() {
      return this.$store.state.spaceId
    }
  },

  watch: {
    searchKey(val) {
      this.searchResult = this.protectFormList.filter(i => {
        const label = i.content.form.label || "";
        return label.includes(val);
      });
    }
  },

  async mounted() {
    const spaceId = this.spaceId
    const { data: res } = await this.$axios(`/magicflu/service/s/json/${spaceId}/forms/feed?start=0&limit=-1&forApp=true&bq=(workspaceId,eq,${spaceId})and(updated,orderby,desc)`);
    if (!res.feed) return;
    const result = Array.isArray(res.feed.entry)
      ? res.feed.entry
      : [res.feed.entry];
    this.protectFormList = result;
    this.searchResult = result;
    const formId = result[0].id;
    const { data: _form } = await this.$axios.get(`/magicflu/service/s/${spaceId}/component/protectconfig?objectType=form&objectId=${formId}`);
    this.currentProtectForm = _form.entry[0];
    this.protectOpt = this.sortProtectOpt(_form.entry[0].detailSet);
  },

  methods: {
    limitShow(key) {
      if (this.checkMode && key !== "trigger" && key !== "report") return false;
      if (limitStatusArr.includes(key)) {
        return false;
      }
      return true;
    },

    async handleFormSelect(index) {
      console.log(index);
      const formId = this.searchResult[index].id;
      const spaceId = this.spaceId;
      const { data: res } = await this.$axios.get(`/magicflu/service/s/${spaceId}/component/protectconfig?objectType=form&objectId=${formId}`);
      if (res.entry.length) {
        console.log(res.entry[0]);
        this.currentProtectForm = res.entry[0];
        this.protectOpt = this.sortProtectOpt(res.entry[0].detailSet);
      }
    },

    async handleProtectTabChange(key) {
      const spaceId = this.spaceId;

      if (key === "form") {
        const formId = this.protectFormList[0].id;
        const { entry = [] } = (await this.$axios.get(`/magicflu/service/s/${spaceId}/component/protectconfig?objectType=form&forApp=true&objectId=${formId}`)).data;
        if (entry.length) {
          this.protectOpt = this.sortProtectOpt(entry[0].detailSet);
        }
      } else {
        const { entry = [] } = (await this.$axios.get(`/magicflu/service/s/${spaceId}/component/protectconfig?objectType=${key}&forApp=true`)).data;
        if (entry.length) {
          const _entry = entry.map(i => ({
            ...i,
            detail: JSON.parse(i.detailSet)
          }));
          this.protectOpt = _entry;
        } else {
          this.protectOpt = [];
        }
      }
    },

    handleCheckAllChange(val) {
      console.log(val);
      this.checkList = val
        ? this.searchResult.map(i => i.content.form.label)
        : [];
      this.isIndeterminate = false;
    },

    handleCheckedCitiesChange(value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.searchResult.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.searchResult.length;
    },

    hanleShowTemp(val, item = [], key) {
      if (val.limit === 3) return;
      if (this.protectKey === "form") {
        if (this.checkMode) return;
        if (key !== "trigger" && key !== "report") {
          console.log("template", item);
          this.template = item;
          this.template.key = key;
          this.templateVisible = true;
          return;
        }
      }
    },

    sortProtectOpt(detailSet) {
      const protectOptRes = {};
      const _protectOpt = JSON.parse(detailSet);
      for (const key in this.protectItems) {
        protectOptRes[key] = _protectOpt[key];
      }
      return protectOptRes;
    },

    // 保存
    async handleSaveOpt(status, item = [], key) {
      console.log(status, item, key);
      let params = {
        forApp: true
      };
      const spaceId = this.spaceId
      if (this.protectKey === "form") {
        if (this.checkMode) return;
        if (status === 2 && key !== "trigger" && key !== "report") {
          this.template = item;
          this.template.key = key;
          this.templateVisible = true;
          return;
        }
        params.objectType = this.currentProtectForm.objectType;
        params.objectId = this.currentProtectForm.objectId;
        params.detailSet = JSON.stringify(this.protectOpt);
        await this.$axios.post(`/magicflu/service/s/${spaceId}/component/protectconfig`, params)
      } else {
        const opt = this.protectOpt[key] || {};
        params = {
          objectId: opt.objectId,
          objectType: opt.objectType,
          detailSet: JSON.stringify(opt.detail),
          forApp: true
        };
        await this.$axios.post(`/magicflu/service/s/${spaceId}/component/protectconfig`, params);
      }
    },

    saveAll() {
      if (!this.checkList.length) {
        // customAlert("至少勾选一个表单");
        console.log("至少勾选一个表单");
        return;
      }
      const formMap = {};
      const ids = [];
      this.protectFormList.forEach(i => {
        formMap[i.content.form.label] = i.id;
      });
      for (const name of this.checkList) {
        ids.push(formMap[name]);
      }
      for (let i in this.protectOpt) {
        // ？
        this.protectOpt[i].templates ? (this.protectOpt[i].templates = []) : "";
      }
      let params = {
        objectType: "form",
        objectId: ids.join("#"),
        detailSet: JSON.stringify(this.protectOpt),
        forApp: true
      };
      this.$axios.post(`/magicflu/service/s/${spaceId}/component/protectconfig`, params)
        .then(({ data: res }) => {
          if (res.errmsg) {
            // customAlert(res.errmsg);
            console.log(res.errmsg);
            return;
          }
          this.checkList = [];
          // customAlert("保存成功");
          console.log("保存成功");
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.checkBox {
  display: flex;
  flex-direction: column;

  .el-checkbox {
    box-sizing: border-box;
    padding: 10px 20px;
    height: 56px;
  }
}

.el-form {
  width: 600px;
}

.el-tabs {
  height: 100%;
}

.el-menu-item.is-active {
  color: var(--el-color-primary);
  background-color: #fafafc;
}

.protect-form {
  box-sizing: border-box;
  margin-top: 20px;
  position: relative;
  padding: 30px;
  height: 90%;
  background-color: #fafafc;
  overflow-y: auto;
}

.form-buttons {
  display: flex;
  justify-content: end;
  margin-bottom: 20px;
}

.save-button {
  position: absolute;
  right: 20px;
  top: 10px;
}

.form-container {
  display: flex;
  height: 100%;

  .form-contain {
    margin-right: 30px;
    width: 250px;
  }

  .form-list {
    border-radius: 4px;
    border: solid 1px #dddddd;
    margin-top: 20px;
    height: 90%;
    overflow: auto;
  }
}

::-webkit-scrollbar {
  width: 10px;
  height: 16px;
  background-color: #f5f5f5;
}

::-webkit-scrollbar-thumb {
  border-radius: 10px;
  border-radius: 0px 5px 5px 0px;
  background: #dddddd;
}
</style>
